/*
*
*/

var ioClient = require('socket.io-client');
var ConstDef = require('./commonDef.js');
var Utils = require("./utils.js");

/**
* Module exports.
*/
module.exports = SIOClient;
/**
* Default config
*/
var config={
	'port':3129,
	'server':'localhost'
}

function SIOClient(){
	this.version='0.1.0';
	this._socket = null;
	this.sessionId = '';
}


SIOClient.prototype.connect = function(configuration){
	
	if(configuration){
		config = configuration;
	}
	//var socket = new ioClient('http://www.ehangsoft.cn:3129');
	var uri = "";
	if(config.server.indexOf("http://") == -1 && config.server.indexOf("https://") == -1){
		uri = "http://"+config.server;
		if(config.port != 80){
			uri+= ":"+config.port;
		}
	}

	var socket = new ioClient(uri);
	this._socket = socket;
	socket.on('connect',function(data){
       console.log('Connect to sucessful. %s.',data);	
       socket.emit(ConstDef.EVENT_CLIENT_LOGIN, { uid: 'vincent' ,sessionId:config.sessionId});	
	});

	socket.on(ConstDef.EVENT_SERVER_ASSIGNSESSION,function(data){ 
		console.log('Server assignSession:%s',data.sessionId);
		config.sessionId = data.sessionId;
		Utils.writeConfig('./config.json',config);
	});
	socket.on(ConstDef.EVNET_MESSAGE,function(data){console.log('Server send %s.',data);});
	socket.on('disconnect',function(data){console.log('Dis-Connect to sucessful. %s.',data);});
    console.log('Connecting to %s.',uri);
};